package com.asset.dispoal.nature.service.commom;

import com.asset.dispoal.nature.domain.db.entity.GbNature;
import com.asset.dispoal.nature.domain.db.mapper.GbNatureMapper;
import com.asset.dispoal.nature.dto.requset.GbNatureRequest;
import com.asset.dispoal.nature.service.converter.GbNatureConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.date.DateTimeUtil;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.util.List;

/**
 * @author qr
 * @date 2022/2/25$
 */
@Component
public class InsertNatureCommand implements BaseCommand<GbNatureRequest, Result> {

    @Autowired
    GbNatureMapper gbNatureMapper;

    @Autowired
    BaseIdeable<String> snowFlake;

    @Override
    public Result execute(GbNatureRequest gbNatureRequest) {
        final GbNature gbNature = GbNatureConverter.INSTANCE.reqToDo(gbNatureRequest);
        final List<GbNature> query = gbNatureMapper.queryList(gbNature);
        if (CollectionUtil.isNotEmpty(query) && query.size() > 1 && !query.get(0).getId().equals(gbNature.getId())) {
            return Result.faild("性质编码 或 性质名称重复");
        }
        final String userId = GlobalHeaderThreadLocal.getOrException().getUserId();
        final String generateId = snowFlake.generateId();
        gbNature.setId(generateId);
        gbNature.setCreateUser(userId);
        gbNature.setCreateTime(DateTimeUtil.currentDate());
        gbNatureMapper.insert(gbNature);
        return Result.ok();
    }
}
